<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Customers
 *
 * @author tuankiet
 */
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');

class Customers extends AppModel {

    public $primaryKey = 'Id';
    //put your code here
    public $validate = array(
        'CustId' => array(
            'notEmpty' => array(
                'rule' => array('notEmpty'),
                'message' => 'IDを入力してください。',
            ),
            'unique' => array(
                'rule' => 'isUnique',
                'required' => 'create',
                'message' => 'このIDが登録されています',
            ),
            'lenght' => array(
                'rule' => array('maxLength', 20),
                'message' => '20桁以下で入力して下さい。'
            ),
            'single_bye'=>array(
                'rule'=>'/^[\w\d\s.,-]*$/',
                'message'=>'英数字で入力してください。'
            ),
        ),
        'CustName' => array(
            'notEmpty' => array(
                'rule' => array('notEmpty'),
                'message' => '名前を入力してください。',
            ),
            'lenght' => array(
                'rule' => array('detecedUtf8Character', 100),
                'message' => '100桁以下で入力して下さい。'
            )
        ),
        'CustAddress' => array(
            'notEmpty' => array(
                'rule' => array('notEmpty'),
                'message' => '住所を入力してください。',
            ),
            'lenght' => array(
                'rule' => array('detecedUtf8Character', 200),
                'message' => '200桁以下で入力して下さい。'
            )
        ),
        'CustFurigana' => array(
            'rexgex' => array(
                'rule' => '/^[ー \p{Katakana}]+$/u',
                //'rule' => '/[^\p{Han}]+$/u',
                'message' => '全角カタカナで入力してください。',
                'allowEmpty' => true
            ),
            'lenght' => array(
                'rule' => array('detecedUtf8Character', 100),
                'message' => '200桁以下で入力して下さい。'
            )
        ),
        'CustPhone' => array(
            'phone' => array(
                'rule' => '/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/',
                'message' => '電話番号は数字で入力してください。',
                'allowEmpty' => true
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
            'lenght' => array(
                'rule' => array('maxLength', 20),
                'message' => '20桁以下で入力して下さい。'
            )
        ),
        'Email' => array(
            'notEmpty' => array(
                'rule' => array('notEmpty'),
                'message' => 'メールアドレスを入力してください。',
            ),
            'unique' => array(
                'rule' => 'isUnique',
                'required' => 'create',
                'message' => 'このメールが登録されていました。',
                'on' => 'create'
            ),
            'ruleEmail' => array(
                'rule' => '/^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$/',
                'message' => 'メールの形式が正しく入力してください。'
            ),
            'lenght' => array(
                'rule' => array('maxLength', 100),
                'message' => '100桁以下で入力して下さい。'
            )
        ),
        'Pass' => array(
            'notEmpty' => array(
                'rule' => 'notEmpty',
                'message' => 'パスワードを入力してください。',
                'on' => 'create'
            ),
            'lenght' => array(
                'rule' => array('maxLength', 50),
                'message' => '50桁以下で入力して下さい。'
            )
        ),
        'ConfirmPass' => array(
            'compare' => array(
                'rule' => array('validate_passwords'),
                'message' => '入力したパスワードが一致しません。',
            ),
            'lenght' => array(
                'rule' => array('maxLength', 50),
                'message' => '50桁以下で入力して下さい。'
            )
        ),
        'ChargePerson' => array(
            'lenght' => array(
                'rule' => array('detecedUtf8Character', 100),
                'message' => '100桁以下で入力して下さい。'
            )
        )
    );

    public function isPhone($params) {
        if (preg_match('/^[^0-9]$/', $params['CustPhone'])) {
            return false;
        }
        return true;
    }

    public function validateEmail($param) {
        return filter_var($param['Email'], FILTER_VALIDATE_EMAIL);
    }
    public function detecedUtf8Character($param,$lenght){
        $value=  array_values($param);
        if(strlen(utf8_decode($value['0']))>$lenght)
            return false;
        return true;
    }

    public function validate_passwords() {
        return $this->data[$this->alias]['Pass'] === $this->data[$this->alias]['ConfirmPass'];
    }

    public function beforeSave($options = array()) {
        parent::beforeSave($options);
        if (!empty($this->data[$this->alias]['Pass'])) {
            $passwordHasher = new SimplePasswordHasher(array('hashType' => 'md5'));
            $this->data[$this->alias]['Pass'] = $passwordHasher->hash(
                    $this->data[$this->alias]['Pass']
            );
        } else {
            unset($this->data[$this->alias]['Pass']);
        }
        foreach ($this->data[$this->alias] as $key => $value) {
            $this->data[$this->alias][$key]=  trim($value);
        }
        return true;
    }

    public function saveData($data, $id = null) {

        if ($id) {
            $this->id = $id;
        } else {
            $this->create();
        }
        $this->set($data);
        if ($this->validates()) {
            return $this->save();
        }
    }

    public function getData($condition = null, $id = null) {
        if (empty($id)) {
            return $this->find('all', array('conditions' => $condition));
        } else {
            return $this->find('first', array(
                        'conditions' => array_merge(array('Customers.Id ' => $id))
                            )
            );
        }
    }

    /**
     * 
     */
    public function getListCustomer($is_search) {
        $user = CakeSession::read("Auth.User");
        $condition = array('IsAdmin' => 0);
        $data = array();
        if (!$user['IsAdmin']) {
            $condition['Customers.Id'] = $user['Id'];
        }

        $data = $this->find('list', array('conditions' => $condition, 'fields' => array('Id', 'CustName')));
        if ($is_search && !isset($condition['Customers.Id'])) {
            $data[0] = 'すべて';
        }
        ksort($data);
        return $data;
    }

    public function getCustByEmail($email) {
        return $this->find('first', array('conditions' => array(
                        'Email' => $email
        )));
    }

}
